const express = require('express'); //引入express
const router = express.Router(); //引入express路由
const DB = require('../db/db'); //引入数据库
let util = require('./../common/util'); // 引入时间处理工具类
let createDate = new Date().Format('yyyy-MM-dd hh:mm:ss'); // 生成订单创建时间

/* GET home page. */
router.get('/', function(req, res, next) {
	console.log('订单时间', createDate);
	console.log('订单号', util.orderCode());
	console.log('订单过期时间',util.timeHandle())
	res.render('index', {
		title: 'Express111'
	});
});
/**
 * 获取省/市/区
 */
router.get('/api/getCity', async (req, res) => {
	const data = require('../data/level-data');
	res.json(data)
})
/**
 * 添加收货地址
 */
router.post('/api/addAddress', async (req, res) => {
	// console.log(JSON.parse(req.body.data))
	// 1. 获取客户端传过来的收货地址信息
	let {
		id,
		consignee,
		phone,
		area_id,
		area_text,
		address,
		tag,
		is_default
	} = JSON.parse(req.body.data);
	console.log(id, consignee, phone, area_id, area_text, address, tag, is_default)
	let content = [];
	// 修改默认地址
	if (is_default == 1) {
		// 1. 查询数据
		let sql = "UPDATE address SET " + "is_default = " + 0;
		let results = await DB.query(sql, content);
	}
	// 2. 查询数据
	let sql = "SELECT * FROM address WHERE id = '" + id + "' LIMIT 1";
	let results = await DB.query(sql, content);
	if (results) {
		// 过滤RowDataPacket
		results = JSON.parse(JSON.stringify(results));
		if (results[0] && !!results) { // 2.1 收货地址存在
			// 2.1.1 更新收货地址数据
			let sql =
				'UPDATE address SET consignee=?, phone=? ,area_id=? ,area_text=? ,address=? ,tag=? ,is_default=? WHERE id=' + id;
			content.push(consignee, phone, JSON.stringify(area_id), area_text, address, tag, is_default)
			let data = await DB.query(sql, content);
			if (data) {
				res.json({
					success_code: 200,
					message: '更新收货地址成功!'
				});
			} else {
				res.json({
					err_code: 0,
					message: '更新收货地址失败!'
				});
			}

		} else { // 2.2 收货地址不存在
			// 2.2.1 新增收货地址
			let update = 'ALTER TABLE address AUTO_INCREMENT = 1';
			let da = await DB.query(update, content);
			let sql =
				"INSERT INTO address(id, consignee, phone, area_id, area_text, address, tag, is_default) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
			content = [id, consignee, phone, JSON.stringify(area_id), area_text, address, tag, is_default];
			let results = await DB.query(sql, content);
			if (results) {
				res.json({
					success_code: 200,
					message: '添加收货地址成功!'
				});
			} else {
				res.json({
					err_code: 0,
					message: '添加收货地址失败!'
				});
			}
		}
	}
})
/**
 * 查询收货地址数据
 */
router.get('/api/getAddress', async (req, res) => {
	let id = req.query.data
	console.log(id)
	// 1.1 数据库查询的语句
	let content = [];
	let sql = "SELECT * FROM address";
	if (id) {
		sql += ' WHERE id = ' + id
	}
	sql += " ORDER BY is_default DESC";
	let results = await DB.query(sql, content);
	res.json(results)
})
/**
 * 查询默认收货地址
 */
router.get('/api/getIs_default', async (req, res) => {
	// 1.1 数据库查询的语句
	let content = [];
	let sql = "SELECT * FROM address WHERE is_default = 1";
	let results = await DB.query(sql, content);
	res.json(results)
})
/**
 * 删除购物车数据
 */
router.post('/api/deleteAddress', async (req, res) => {
	let id = req.body.data
	let content = [];
	// 1.1 删除数据语句
	let sql = "DELETE FROM address WHERE id = " + id
	let results = await DB.query(sql, content);
	if (results) {
		res.json({
			success_code: 200,
			message: '删除成功'
		});
	} else {
		res.json({
			err_code: 0,
			message: '删除失败!'
		});
	}
})

/**
 * 新增订单
 */
router.post('/api/addOrder', async (req, res) => {
	let data = JSON.parse(req.body.data)
	let content = [];
	let {
		product,
		status,
		addressId,
		remark,
		totalPrice
	} = data
	let orderid = util.orderCode() //订单号
	let createtime = new Date().Format('yyyy-MM-dd hh:mm:ss') //创建时间
	let overtime = util.timeHandle()
	console.log('创建订单时间',createtime)
	//插入主表
	let sql =
		"INSERT INTO orders(orderid, status, addressId, remark, totalPrice, createtime) VALUES (?, ?, ?, ?, ?, ?)";
	content = [orderid, status, addressId, remark, totalPrice, createtime];
	let results = await DB.query(sql, content);

	//插入子表
	product.forEach(item => {
		item.unshift(orderid)
	})
	let sql1 = "INSERT INTO order_product(orderid, num, price, goodsId) VALUES ?";
	let results1 = await DB.query(sql1, [product]);
	//返回数据
	res.json({
		success_code: 200,
		message: orderid
	});
})
/**
 * 查询订单列表
 */
router.post('/api/getOrder', async (req, res) => {
	console.log(req.body.data)
	let id = req.body.data;
	let content = []
	console.log(parseInt(id))
	//订单表
	let sql = 'SELECT * FROM orders'
	if (parseInt(id) && id.length < 5 && !!id) {
		console.log('进入')
		sql += ' WHERE status =' + id
	}else if(id.length > 10){
		console.log('进入1')
		sql += ' WHERE orderid =' + id
	}
	
	let results = await DB.query(sql, content);
	results = JSON.parse(JSON.stringify(results));
	//订单商品表
	let sql1 = 'SELECT s.*, c.num,c.orderid FROM recommend as s right join order_product as c on s.id = c.goodsId';
	let results1 = await DB.query(sql1, content);
	results1 = JSON.parse(JSON.stringify(results1));
	
	//查询收货地址
	if(results && id.length > 10){
		let sql2 = 'SELECT * FROM address WHERE id=' + results[0].addressId;
		var results2 = await DB.query(sql2, content);
		results2 = JSON.parse(JSON.stringify(results2));
	}

	//进入订单时更新过期商品状态(未付款)
	let sql3 = 'UPDATE orders SET status = 60 WHERE UNIX_TIMESTAMP(createtime)+1800 < UNIX_TIMESTAMP() AND status = 10';
	let results3 = await DB.query(sql3, content);
	
	//遍历合并
	results.forEach(item => {
		item.product = [];
		item.createtime = new Date(item.createtime).Format('yyyy-MM-dd hh:mm:ss');
		if(results && id.length > 10) item.address = results2;
		results1.forEach(item1 => {
			if (item.orderid == item1.orderid) {
				item.product.push(JSON.stringify(item1))
			}
		})
	})
	res.json(results);
})

/**
 * 查询订单详情
 */
router.post('/api/getOrderDetail', async (req, res) => {
	console.log(req.body.data)
	let id = req.body.data;
	let content = []

	let sql = "SELECT * FROM orders WHERE orderid = " + id
	let results = await DB.query(sql, content);
	results = JSON.parse(JSON.stringify(results));
	results[0].createtime = new Date(results[0].createtime).Format('yyyy-MM-dd hh:mm:ss');
	console.log(results)
	res.json(results);
})
/**
 * 删除订单
 */
router.post('/api/deleteOrder', async (req, res) => {
	let id = req.body.data
	let content = [];
	// 1.1 删除数据语句
	let sql =
		"DELETE orders,order_product from orders LEFT JOIN order_product ON orders.orderid=order_product.orderid WHERE orders.orderid=" +
		id
	let results = await DB.query(sql, content);
	if (results) {
		res.json({
			success_code: 200,
			message: '删除成功'
		});
	} else {
		res.json({
			err_code: 0,
			message: '删除失败!'
		});
	}

})
module.exports = router;
